import { Injectable } from '@nestjs/common';
import { InjectModel } from '@nestjs/mongoose';
import { User } from './user.interface';
import { Model } from 'mongoose';
import { CreateUserDTO, EditUserDTO } from './user.dto';
const request = require('request');


@Injectable()
export class UserService {
    constructor(@InjectModel('user') private readonly userModel: Model<User>){

    }

    async findAll(): Promise<User[]> {
        return await this.userModel.find();
    }

    async findWhere(filter?: object): Promise<User[]> {
        return await this.userModel.find(filter);
    }

    async findUser(filter?: { code?: string}): Promise<User[]> {
        return new Promise((resolve, reject) => {
            const url = `https://api.weixin.qq.com/sns/jscode2session?appid=wxf91075081022b5c6&secret=04efc2f82da907a6716adba558653306&js_code=${filter?.code}&grant_type=authorization_code`;
        // 对url发出一个get请求
            request.get({
            'url': url
            }, (error, response, body) => {
                error && reject(error);
                let abody = JSON.parse(body);
                resolve(abody);
            })
            })
    }

    async find(id: string): Promise<User> {
        return await this.userModel.findById(id);
    }
    
    async addone(body: CreateUserDTO): Promise<User> {
        return await this.userModel.create(body);
    }

    async editone(id: string, body: EditUserDTO): Promise<User> {
        return await this.userModel.findByIdAndUpdate(id, body);
    }
    
    async delete(id: string): Promise<User> {
        return await this.userModel.findByIdAndDelete(id);
    }
}
